/**
 * 待办事项相关Mock数据
 */

import { generateId, randomNumber, randomChoice, randomDate, randomBoolean, formatDate, paginate } from '../utils'
import { TODOS_CONFIG } from '@/config'

// 模拟待办事项数据
const mockTodos = []

// 模拟待办分类数据
const mockTodoCategories = TODOS_CONFIG.CATEGORIES.map(category => ({
  id: generateId(),
  ...category,
  isCustom: false,
  createdAt: '2024-01-01T00:00:00.000Z',
  updatedAt: '2024-01-01T00:00:00.000Z'
}))

// 模拟待办标签数据
const mockTodoTags = [
  { name: '工作', color: '#e74c3c' },
  { name: '学习', color: '#3498db' },
  { name: '生活', color: '#2ecc71' },
  { name: '健康', color: '#f39c12' },
  { name: '娱乐', color: '#9b59b6' },
  { name: '紧急', color: '#c0392b' }
].map(tag => ({
  id: generateId(),
  ...tag,
  isCustom: false,
  createdAt: '2024-01-01T00:00:00.000Z',
  updatedAt: '2024-01-01T00:00:00.000Z'
}))

// 生成模拟待办事项
function generateTodos() {
  const todoTitles = [
    '完成项目报告', '准备会议材料', '回复客户邮件', '更新产品文档',
    '学习新技术', '阅读技术文章', '整理代码库', '优化系统性能',
    '锻炼身体', '买菜做饭', '打扫房间', '洗衣服',
    '看电影', '听音乐', '和朋友聚会', '计划旅行',
    '缴费账单', '预约体检', '维修电器', '购买日用品'
  ]
  
  for (let i = 0; i < 50; i++) {
    const category = randomChoice(mockTodoCategories)
    const isCompleted = randomBoolean(0.3) // 30%的概率已完成
    const createdDate = randomDate(new Date(2024, 0, 1), new Date())
    const dueDate = randomBoolean(0.7) ? randomDate(createdDate, new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)) : null
    const completedDate = isCompleted ? randomDate(createdDate, dueDate || new Date()) : null
    
    mockTodos.push({
      id: generateId(),
      title: randomChoice(todoTitles),
      description: randomChoice(['', '这是一个重要的任务', '需要仔细处理', '优先级较高', '可以延后处理'], 1),
      categoryId: category.id,
      categoryName: category.name,
      priority: randomChoice(TODOS_CONFIG.PRIORITIES).id,
      status: isCompleted ? 'completed' : randomChoice(['pending', 'in_progress']),
      tags: (() => {
        const tagCount = randomNumber(0, 3)
        if (tagCount === 0) return []
        const selectedTags = randomChoice(mockTodoTags, tagCount)
        return Array.isArray(selectedTags) ? selectedTags.map(tag => tag.name) : [selectedTags.name]
      })(),
      dueDate: dueDate ? dueDate.toISOString() : null,
      reminder: randomBoolean(0.4) && dueDate ? {
        enabled: true,
        time: new Date(dueDate.getTime() - randomChoice([15, 30, 60, 120]) * 60 * 1000).toISOString(),
        type: randomChoice(['notification', 'email'])
      } : null,
      isImportant: randomBoolean(0.2),
      isUrgent: randomBoolean(0.3),
      estimatedDuration: randomChoice([15, 30, 60, 120, 240]), // 分钟
      actualDuration: isCompleted ? randomNumber(10, 300) : null,
      progress: isCompleted ? 100 : randomNumber(0, 80),
      subtasks: generateSubtasks(randomNumber(0, 3)),
      attachments: [],
      notes: randomChoice(['', '需要注意的事项', '相关资源链接', '进度更新'], 1),
      createdAt: createdDate.toISOString(),
      updatedAt: (completedDate || createdDate).toISOString(),
      completedAt: completedDate ? completedDate.toISOString() : null
    })
  }
  
  // 按创建时间倒序排列
  mockTodos.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
}

// 生成子任务
function generateSubtasks(count) {
  const subtasks = []
  const subtaskTitles = [
    '收集资料', '分析需求', '制定计划', '执行任务', '检查结果',
    '准备材料', '联系相关人员', '确认细节', '完成初稿', '审核修改'
  ]
  
  for (let i = 0; i < count; i++) {
    subtasks.push({
      id: generateId(),
      title: randomChoice(subtaskTitles),
      completed: randomBoolean(0.4),
      createdAt: new Date().toISOString()
    })
  }
  
  return subtasks
}

// 初始化待办事项
generateTodos()

export default {
  // 获取待办事项列表
  'GET /todos': async (params = {}) => {
    const { 
      page = 1, 
      pageSize = 20, 
      status, 
      categoryId, 
      priority, 
      tags, 
      dueDate, 
      isImportant, 
      isUrgent,
      search
    } = params
    
    let filteredTodos = [...mockTodos]
    
    // 按状态筛选
    if (status) {
      filteredTodos = filteredTodos.filter(todo => todo.status === status)
    }
    
    // 按分类筛选
    if (categoryId) {
      filteredTodos = filteredTodos.filter(todo => todo.categoryId === categoryId)
    }
    
    // 按优先级筛选
    if (priority) {
      filteredTodos = filteredTodos.filter(todo => todo.priority === priority)
    }
    
    // 按标签筛选
    if (tags && tags.length > 0) {
      filteredTodos = filteredTodos.filter(todo => 
        tags.some(tag => todo.tags.includes(tag))
      )
    }
    
    // 按截止日期筛选
    if (dueDate) {
      const targetDate = formatDate(new Date(dueDate), 'YYYY-MM-DD')
      filteredTodos = filteredTodos.filter(todo => 
        todo.dueDate && formatDate(new Date(todo.dueDate), 'YYYY-MM-DD') === targetDate
      )
    }
    
    // 按重要性筛选
    if (isImportant !== undefined) {
      filteredTodos = filteredTodos.filter(todo => todo.isImportant === isImportant)
    }
    
    // 按紧急性筛选
    if (isUrgent !== undefined) {
      filteredTodos = filteredTodos.filter(todo => todo.isUrgent === isUrgent)
    }
    
    // 搜索
    if (search) {
      const searchLower = search.toLowerCase()
      filteredTodos = filteredTodos.filter(todo => 
        todo.title.toLowerCase().includes(searchLower) ||
        todo.description.toLowerCase().includes(searchLower) ||
        todo.notes.toLowerCase().includes(searchLower)
      )
    }
    
    return paginate(filteredTodos, page, pageSize)
  },
  
  // 获取待办事项详情
  'GET /todos/:id': async (params, { pathParams }) => {
    const { id } = pathParams
    const todo = mockTodos.find(todo => todo.id === id)
    
    if (!todo) {
      throw new Error(JSON.stringify({ code: 1003, message: '待办事项不存在' }))
    }
    
    return todo
  },
  
  // 创建待办事项
  'POST /todos': async (data) => {
    const { 
      title, 
      description, 
      categoryId, 
      priority, 
      tags, 
      dueDate, 
      reminder, 
      isImportant, 
      isUrgent,
      estimatedDuration,
      subtasks
    } = data
    
    // 验证必填字段
    if (!title) {
      throw new Error(JSON.stringify({ code: 1001, message: '标题不能为空' }))
    }
    
    // 验证分类是否存在
    let category = null
    if (categoryId) {
      category = mockTodoCategories.find(cat => cat.id === categoryId)
      if (!category) {
        throw new Error(JSON.stringify({ code: 1003, message: '分类不存在' }))
      }
    }
    
    // 验证优先级
    if (priority && !TODO_CONFIG.PRIORITIES.includes(priority)) {
      throw new Error(JSON.stringify({ code: 1001, message: '无效的优先级' }))
    }
    
    const newTodo = {
      id: generateId(),
      title,
      description: description || '',
      categoryId: categoryId || null,
      categoryName: category ? category.name : null,
      priority: priority || 'medium',
      status: 'pending',
      tags: tags || [],
      dueDate: dueDate || null,
      reminder: reminder || null,
      isImportant: isImportant || false,
      isUrgent: isUrgent || false,
      estimatedDuration: estimatedDuration || null,
      actualDuration: null,
      progress: 0,
      subtasks: subtasks || [],
      attachments: [],
      notes: '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      completedAt: null
    }
    
    mockTodos.unshift(newTodo)
    
    return newTodo
  },
  
  // 更新待办事项
  'PUT /todos/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const todoIndex = mockTodos.findIndex(todo => todo.id === id)
    
    if (todoIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '待办事项不存在' }))
    }
    
    const allowedFields = [
      'title', 'description', 'categoryId', 'priority', 'status', 'tags', 
      'dueDate', 'reminder', 'isImportant', 'isUrgent', 'estimatedDuration', 
      'actualDuration', 'progress', 'subtasks', 'notes'
    ]
    
    const updates = {}
    
    allowedFields.forEach(field => {
      if (data[field] !== undefined) {
        updates[field] = data[field]
      }
    })
    
    // 如果更新了分类，需要更新分类名称
    if (updates.categoryId) {
      const category = mockTodoCategories.find(cat => cat.id === updates.categoryId)
      if (!category) {
        throw new Error(JSON.stringify({ code: 1003, message: '分类不存在' }))
      }
      updates.categoryName = category.name
    }
    
    // 如果状态变为已完成，设置完成时间
    if (updates.status === 'completed' && mockTodos[todoIndex].status !== 'completed') {
      updates.completedAt = new Date().toISOString()
      updates.progress = 100
    }
    
    // 如果状态从已完成变为其他状态，清除完成时间
    if (updates.status && updates.status !== 'completed' && mockTodos[todoIndex].status === 'completed') {
      updates.completedAt = null
    }
    
    mockTodos[todoIndex] = {
      ...mockTodos[todoIndex],
      ...updates,
      updatedAt: new Date().toISOString()
    }
    
    return mockTodos[todoIndex]
  },
  
  // 删除待办事项
  'DELETE /todos/:id': async (data, { pathParams }) => {
    const { id } = pathParams
    const todoIndex = mockTodos.findIndex(todo => todo.id === id)
    
    if (todoIndex === -1) {
      throw new Error(JSON.stringify({ code: 1003, message: '待办事项不存在' }))
    }
    
    mockTodos.splice(todoIndex, 1)
    
    return { message: '删除成功' }
  },
  
  // 批量操作待办事项
  'POST /todos/batch': async (data) => {
    const { action, ids, updates } = data
    
    if (!action || !ids || !Array.isArray(ids)) {
      throw new Error(JSON.stringify({ code: 1001, message: '参数错误' }))
    }
    
    const results = []
    
    for (const id of ids) {
      const todoIndex = mockTodos.findIndex(todo => todo.id === id)
      if (todoIndex === -1) {
        results.push({ id, success: false, message: '待办事项不存在' })
        continue
      }
      
      try {
        switch (action) {
          case 'delete':
            mockTodos.splice(todoIndex, 1)
            results.push({ id, success: true, message: '删除成功' })
            break
            
          case 'complete':
            mockTodos[todoIndex] = {
              ...mockTodos[todoIndex],
              status: 'completed',
              progress: 100,
              completedAt: new Date().toISOString(),
              updatedAt: new Date().toISOString()
            }
            results.push({ id, success: true, message: '标记完成成功' })
            break
            
          case 'update':
            if (updates) {
              mockTodos[todoIndex] = {
                ...mockTodos[todoIndex],
                ...updates,
                updatedAt: new Date().toISOString()
              }
            }
            results.push({ id, success: true, message: '更新成功' })
            break
            
          default:
            results.push({ id, success: false, message: '不支持的操作' })
        }
      } catch (error) {
        results.push({ id, success: false, message: error.message })
      }
    }
    
    return { results }
  },
  
  // 获取待办分类
  'GET /todos/categories': async () => {
    return mockTodoCategories
  },
  
  // 创建待办分类
  'POST /todos/categories': async (data) => {
    const { name, icon, color } = data
    
    // 验证必填字段
    if (!name) {
      throw new Error(JSON.stringify({ code: 1001, message: '分类名称不能为空' }))
    }
    
    // 检查名称是否已存在
    if (mockTodoCategories.find(category => category.name === name)) {
      throw new Error(JSON.stringify({ code: 1004, message: '分类名称已存在' }))
    }
    
    const newCategory = {
      id: generateId(),
      name,
      icon: icon || 'list',
      color: color || '#34495e',
      isCustom: true,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockTodoCategories.push(newCategory)
    
    return newCategory
  },
  
  // 获取待办标签
  'GET /todos/tags': async () => {
    return mockTodoTags
  },
  
  // 创建待办标签
  'POST /todos/tags': async (data) => {
    const { name, color } = data
    
    // 验证必填字段
    if (!name) {
      throw new Error(JSON.stringify({ code: 1001, message: '标签名称不能为空' }))
    }
    
    // 检查名称是否已存在
    if (mockTodoTags.find(tag => tag.name === name)) {
      throw new Error(JSON.stringify({ code: 1004, message: '标签名称已存在' }))
    }
    
    const newTag = {
      id: generateId(),
      name,
      color: color || randomChoice(['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c']),
      isCustom: true,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    mockTodoTags.push(newTag)
    
    return newTag
  },
  
  // 获取待办统计
  'GET /todos/stats': async (params = {}) => {
    const { period = 'week' } = params
    
    const now = new Date()
    let startDate, endDate
    
    switch (period) {
      case 'day':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
        endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
        break
      case 'week':
        const weekStart = now.getDate() - now.getDay()
        startDate = new Date(now.getFullYear(), now.getMonth(), weekStart)
        endDate = new Date(now.getFullYear(), now.getMonth(), weekStart + 7)
        break
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1)
        break
      default:
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
        endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
    }
    
    const periodTodos = mockTodos.filter(todo => {
      const todoDate = new Date(todo.createdAt)
      return todoDate >= startDate && todoDate < endDate
    })
    
    const completedTodos = periodTodos.filter(todo => todo.status === 'completed')
    const overdueTodos = mockTodos.filter(todo => {
      if (!todo.dueDate || todo.status === 'completed') return false
      return new Date(todo.dueDate) < now
    })
    
    // 按分类统计
    const categoryStats = {}
    periodTodos.forEach(todo => {
      const categoryName = todo.categoryName || '未分类'
      if (!categoryStats[categoryName]) {
        categoryStats[categoryName] = {
          total: 0,
          completed: 0
        }
      }
      categoryStats[categoryName].total += 1
      if (todo.status === 'completed') {
        categoryStats[categoryName].completed += 1
      }
    })
    
    // 按优先级统计
    const priorityStats = {}
    TODO_CONFIG.PRIORITIES.forEach(priority => {
      priorityStats[priority] = {
        total: periodTodos.filter(todo => todo.priority === priority).length,
        completed: periodTodos.filter(todo => todo.priority === priority && todo.status === 'completed').length
      }
    })
    
    const completionRate = periodTodos.length > 0 ? 
      Math.round((completedTodos.length / periodTodos.length) * 100) : 0
    
    return {
      period,
      totalTodos: periodTodos.length,
      completedTodos: completedTodos.length,
      pendingTodos: periodTodos.filter(todo => todo.status === 'pending').length,
      inProgressTodos: periodTodos.filter(todo => todo.status === 'in_progress').length,
      overdueTodos: overdueTodos.length,
      completionRate,
      categoryStats: Object.entries(categoryStats).map(([name, stats]) => ({
        categoryName: name,
        ...stats,
        completionRate: stats.total > 0 ? Math.round((stats.completed / stats.total) * 100) : 0
      })),
      priorityStats: Object.entries(priorityStats).map(([priority, stats]) => ({
        priority,
        ...stats,
        completionRate: stats.total > 0 ? Math.round((stats.completed / stats.total) * 100) : 0
      }))
    }
  },
  
  // 获取今日待办
  'GET /todos/today': async () => {
    const today = formatDate(new Date(), 'YYYY-MM-DD')
    
    const todayTodos = mockTodos.filter(todo => {
      if (todo.dueDate) {
        return formatDate(new Date(todo.dueDate), 'YYYY-MM-DD') === today
      }
      return false
    })
    
    return todayTodos.sort((a, b) => {
      // 按优先级和状态排序
      const priorityOrder = { high: 3, medium: 2, low: 1 }
      const statusOrder = { pending: 3, in_progress: 2, completed: 1 }
      
      if (a.priority !== b.priority) {
        return priorityOrder[b.priority] - priorityOrder[a.priority]
      }
      
      return statusOrder[b.status] - statusOrder[a.status]
    })
  },
  
  // 获取逾期待办
  'GET /todos/overdue': async () => {
    const now = new Date()
    
    const overdueTodos = mockTodos.filter(todo => {
      if (!todo.dueDate || todo.status === 'completed') return false
      return new Date(todo.dueDate) < now
    })
    
    return overdueTodos.sort((a, b) => new Date(a.dueDate) - new Date(b.dueDate))
  }
}